
/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}


/**
 * 获取当天日期对象
 */
export function getCurDate(){
  var date = new Date() ;
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
  return date;
}

/**
 * 字符串格式化
 * @param fmt 's{0}0{1}xxxxx'
 * @param vars [a, b]=>'sa0bxxxxx'
 */
export function stringFormat(formatted) {
	let args = arguments;
	for(let i = 0; i < (args.length - 1); i++) {
		let regexp = new RegExp('\\{' + i + '\\}', 'gi')
    let a = args[i + 1];
		formatted = formatted.replace(regexp, a||a==0||a==false?a:'')
	}
	return formatted
}

/**
 * 时间格式化
 * @param value
 * @param fmt yyyy-MM-dd hh:mm:ss
 * @returns {*}
 */
export function formatDate(value, fmt) {
  if(!value){
    return value;
  }

  fmt = fmt || 'yyyy-MM-dd hh:mm:ss';

  let date;
  let regPos = /^\d+(\.\d+)?$/;
  if(value instanceof Date){
    date = value;
  }else if(regPos.test(value)){
    //如果是数字
    date = new Date(value);
  }else{
    value = (""+value).trim();
    return value.substr(0,fmt.length);
  }

  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function convertTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  }
  if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  }
  if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  }
  if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  }

  return (
    d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  )
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function object2UrlParam(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getParamFromUrl(url) {
  const search = decodeURIComponent(url.substring(url.lastIndexOf('?') + 1)).replace(/\+/g, ' ')
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    obj[decodeURIComponent($1)+''] = decodeURIComponent($2)+''
    return rs
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

// /**
//  * 构造树型结构数据
//  * @param {*} data 数据源
//  * @param {*} id id字段 默认 'id'
//  * @param {*} parentId 父节点字段 默认 'parentId'
//  * @param {*} children 孩子节点字段 默认 'children'
//  * @param {*} rootId 根Id 默认 0
//  */
// export function handleTree(data, id, parentId, children, rootId) {
// 	id = id || 'id'
// 	parentId = parentId || 'parentId'
// 	children = children || 'children'
// 	rootId = rootId || 0
// 	//对源数据深度克隆
// 	const cloneData = JSON.parse(JSON.stringify(data))
// 	//循环所有项
// 	const treeData = cloneData.filter(father => {
// 		let branchArr = cloneData.filter(child => {
// 			//返回每一项的子级数组
// 			return father[id] === child[parentId]
// 		});
// 		branchArr.length > 0 ? father.children = branchArr : '';
// 		//返回第一层
// 		return father[parentId] === rootId;
// 	});
// 	return treeData != '' ? treeData : data;
// }


/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  let event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}
